<template>
  <div class="dashboard">
    <h2>{{ t('admin.dashboard.title') }}</h2>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-blue">
              <Shop />
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.merchants }}</div>
              <div class="stat-label">{{ t('admin.dashboard.merchants') }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-green">
              <Goods />
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.products }}</div>
              <div class="stat-label">{{ t('admin.dashboard.products') }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-orange">
              <Ticket />
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.exchangeCodes }}</div>
              <div class="stat-label">{{ t('admin.dashboard.exchangeCodes') }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-red">
              <Document />
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.orders }}</div>
              <div class="stat-label">{{ t('admin.dashboard.orders') }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>{{ t('admin.dashboard.merchantGrowth') }}</span>
            </div>
          </template>
          <div ref="growthChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>{{ t('admin.dashboard.subscriptionDistribution') }}</span>
            </div>
          </template>
          <div ref="subscriptionChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最近活动 -->
    <el-row :gutter="20" class="activity-row">
      <el-col :span="12">
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <span>{{ t('admin.dashboard.recentMerchants') }}</span>
            </div>
          </template>
          <el-table :data="recentMerchants" style="width: 100%">
            <el-table-column prop="businessName" :label="t('admin.merchant.businessName')"></el-table-column>
            <el-table-column prop="subscriptionType" :label="t('admin.merchant.subscriptionType')">
              <template #default="scope">
                <el-tag :type="scope.row.subscriptionType === 'PREMIUM' ? 'success' : 'warning'">
                  {{ t(`admin.subscriptions.${scope.row.subscriptionType.toLowerCase()}`) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" :label="t('admin.merchant.createdAt')"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <span>{{ t('admin.dashboard.recentOrders') }}</span>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%">
            <el-table-column prop="orderNumber" :label="t('admin.order.orderNumber')"></el-table-column>
            <el-table-column prop="merchantName" :label="t('admin.order.merchant')"></el-table-column>
            <el-table-column prop="status" :label="t('admin.order.status')">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ t(`admin.order.status.${scope.row.status.toLowerCase()}`) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" :label="t('admin.order.createdAt')"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import { Shop, Goods, Ticket, Document } from '@element-plus/icons-vue'
import { merchantAPI, orderAPI, productAPI, exchangeCodeAPI } from '@/utils/api'

export default {
  name: 'AdminDashboard',
  components: {
    Shop,
    Goods,
    Ticket,
    Document
  },
  setup() {
    const { t } = useI18n()
    const growthChart = ref(null)
    const subscriptionChart = ref(null)
    let growthChartInstance = null
    let subscriptionChartInstance = null
    
    const stats = ref({
      merchants: 0,
      products: 0,
      exchangeCodes: 0,
      orders: 0
    })
    
    const recentMerchants = ref([])
    const recentOrders = ref([])
    
    const loading = ref({
      stats: true,
      merchants: true,
      orders: true
    })
    
    const getOrderStatusType = (status) => {
      const statusTypes = {
        PENDING: 'info',
        CONFIRMED: 'primary',
        PROCESSING: 'warning',
        SHIPPED: 'success',
        DELIVERED: 'success',
        CANCELLED: 'danger'
      }
      return statusTypes[status] || 'info'
    }
    
    const loadDashboardStats = async () => {
      try {
        loading.value.stats = true
        
        // 获取统计数据
        const [merchantsRes, productsRes, exchangeCodesRes, ordersRes] = await Promise.allSettled([
          merchantAPI.getMerchants({ page: 0, size: 1 }), // 只获取总数
          productAPI.getProducts({ page: 0, size: 1 }),
          exchangeCodeAPI.getExchangeCodes({ page: 0, size: 1 }),
          orderAPI.getOrders({ page: 0, size: 1 })
        ])
        
        stats.value.merchants = merchantsRes.status === 'fulfilled' ? (merchantsRes.value.data.totalElements || 0) : 0
        stats.value.products = productsRes.status === 'fulfilled' ? (productsRes.value.data.totalElements || 0) : 0
        stats.value.exchangeCodes = exchangeCodesRes.status === 'fulfilled' ? (exchangeCodesRes.value.data.totalElements || 0) : 0
        stats.value.orders = ordersRes.status === 'fulfilled' ? (ordersRes.value.data.totalElements || 0) : 0
        
      } catch (error) {
        console.error('Error loading dashboard stats:', error)
        // 即使出错也设置为加载完成状态，避免页面卡住
        stats.value = { merchants: 0, products: 0, exchangeCodes: 0, orders: 0 }
      } finally {
        loading.value.stats = false
      }
    }
    
    const loadRecentMerchants = async () => {
      try {
        loading.value.merchants = true
        const response = await merchantAPI.getMerchants({ 
          page: 0, 
          size: 5,
          sort: 'createdAt,desc'  // 假设后端支持这种排序
        })
        recentMerchants.value = Array.isArray(response.data.content) ? 
          response.data.content : 
          (Array.isArray(response.data) ? response.data : [])
      } catch (error) {
        console.error('Error loading recent merchants:', error)
        recentMerchants.value = []
      } finally {
        loading.value.merchants = false
      }
    }
    
    const loadRecentOrders = async () => {
      try {
        loading.value.orders = true
        const response = await orderAPI.getOrders({ 
          page: 0, 
          size: 5,
          sort: 'createdAt,desc'  // 假设后端支持这种排序
        })
        recentOrders.value = Array.isArray(response.data.content) ? 
          response.data.content : 
          (Array.isArray(response.data) ? response.data : [])
      } catch (error) {
        console.error('Error loading recent orders:', error)
        recentOrders.value = []
      } finally {
        loading.value.orders = false
      }
    }
    
    const initCharts = () => {
      // 初始化商家增长图表
      if (growthChart.value) {
        growthChartInstance = echarts.init(growthChart.value)
        growthChartInstance.setOption({
          title: {
            text: t('admin.dashboard.merchantGrowth')
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [12, 15, 18, 22, 25, 28, 30, 32, 35, 38, 40, 42],
            type: 'line',
            smooth: true,
            areaStyle: {}
          }]
        })
      }
      
      // 初始化订阅分布图表
      if (subscriptionChart.value) {
        subscriptionChartInstance = echarts.init(subscriptionChart.value)
        subscriptionChartInstance.setOption({
          title: {
            text: t('admin.dashboard.subscriptionDistribution'),
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [{
            type: 'pie',
            radius: '50%',
            data: [
              { value: 18, name: t('admin.subscriptions.premium') },
              { value: 6, name: t('admin.subscriptions.free') }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        })
      }
    }
    
    const resizeCharts = () => {
      if (growthChartInstance) {
        growthChartInstance.resize()
      }
      if (subscriptionChartInstance) {
        subscriptionChartInstance.resize()
      }
    }
    
    const loadData = async () => {
      await Promise.all([
        loadDashboardStats(),
        loadRecentMerchants(),
        loadRecentOrders()
      ])
      
      // 等待 DOM 更新后初始化图表
      await nextTick()
      initCharts()
    }
    
    onMounted(() => {
      loadData()
      window.addEventListener('resize', resizeCharts)
    })
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeCharts)
      if (growthChartInstance) {
        growthChartInstance.dispose()
      }
      if (subscriptionChartInstance) {
        subscriptionChartInstance.dispose()
      }
    })
    
    return {
      t,
      stats,
      recentMerchants,
      recentOrders,
      growthChart,
      subscriptionChart,
      loading,
      getOrderStatusType
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
}

.bg-blue {
  background-color: #409eff;
}

.bg-green {
  background-color: #67c23a;
}

.bg-orange {
  background-color: #e6a23c;
}

.bg-red {
  background-color: #f56c6c;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 320px;
}

.activity-row {
  margin-bottom: 20px;
}

.activity-card {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>